<template>
  <div class="mobile-content">
    <Collapse v-model="activeNames">
      <CollapseItem title="基本信息" name="1" icon="point-gift">
        <Cell>
          <template #title>
            <span>{{ model.name }}</span>
          </template>
          <template #label>
            种子名称
          </template>
        </Cell>
        <Cell>
          <template #title>
            <span>{{ formatDate(model.addtime) }}</span>
          </template>
          <template #label>
            添加时间
          </template>
        </Cell>
        <Cell>
          <template #title>
            <span>{{ model.address }}</span>
          </template>
          <template #label>
            下载链接
          </template>
        </Cell>
        <Cell>
          <template #title>
            <span>{{ model.torrentFile }}</span>
          </template>
          <template #label>
            种子文件
          </template>
        </Cell>
        <Cell>
          <template #title>
            <span>{{ optionName(model.categoryid, categoryOptions) }} / {{ optionName(model.siteid, siteOptions) }}
            </span>
          </template>
          <template #label>
            所属分类 / 所属站点
          </template>
        </Cell>
        <Cell>
          <template #title>
            <span>{{ model.description }}</span>
          </template>
          <template #label>
            描述
          </template>
        </Cell>
        <Cell>
          <template #title>
            <span>{{ model.tmdbid == 0 ? '无法识别' : (model.tmdbid==-1?'多结果':model.tmdbid) }}</span>
          </template>
          <template #label>
            TMDB ID
          </template>
          <template #right-icon>
            <Button v-if="model.mediaType === 'tv'" plain type="primary" size="mini" @click="showSeasonPicker">
              季: {{ model.season != null ? model.season : '未指定'}}</Button>
          </template>
        </Cell>
        <Cell>
          <template #title>
            <span>{{ model.autoLink ? '是' : '否' }}</span>
            <span v-if="model.libraryid || model.toLink"> | {{ optionName(model.libraryid, libraryOptions) }} / {{
            model.toLink }}
            </span>
          </template>
          <template #label>
            自动链接
          </template>
        </Cell>
        <Cell>
          <template #title>
            <span>{{ model.linkDir ? model.linkDir : '否' }}</span>
          </template>
          <template #label>
            已链接
          </template>
        </Cell>
      </CollapseItem>
      <CollapseItem title="下载信息" name="2" icon="info">
        <Cell>
          <template #title>
            <span>{{ optionName(model.clientid, clientOptions) }}</span>
          </template>
          <template #label>
            下载器
          </template>
        </Cell>
        <Cell>
          <template #title>
            <span>{{ model.hashString }}</span>
          </template>
          <template #label>
            HASH
          </template>
        </Cell>
        <template v-if="model.status === 'unlink'">
          <Empty description="还未推送至下载器" />
        </template>
        <template v-else>
          <Cell :border="false">
            <Row gutter="10">
              <Col span="8">
              <Button icon="play" type="success" block size="small" @click="doAction('start')"
                :loading="doActioning">开始</Button>
              </Col>
              <Col span="8">
              <Button icon="pause" type="warning" block size="small" @click="doAction('stop')"
                :loading="doActioning">停止</Button>
              </Col>
              <Col span="8">
              <Button icon="replay" type="primary" block size="small" @click="loadInfoInClient">刷新</Button>
              </Col>
            </Row>
          </Cell>
          <Empty v-if="!info.client" image="network" description="下载信息获取失败" />
          <template v-else>
            <!-- <Cell>
              <template #title>
                <span>{{  info.client?.type  }} - {{  info.client?.address  }}</span>
              </template>
              <template #label>
                下载器
              </template>
            </Cell> -->
            <Cell>
              <template #title>
                <span>{{ info.id }}</span>
              </template>
              <template #label>
                ID
              </template>
            </Cell>
            <Cell>
              <template #title>
                <span>{{ formatDate(parseInt(info.addedDate) * 1000) }}</span>
              </template>
              <template #label>
                添加时间
              </template>
            </Cell>
            <Cell>
              <template #title>
                <span>{{ info.name }}</span>
              </template>
              <template #label>
                名称
              </template>
            </Cell>
            <Cell>
              <template #title>
                <span>{{ info.hashString }}</span>
              </template>
              <template #label>
                HASH
              </template>
            </Cell>
            <Cell>
              <template #title>
                <span>{{ info.downloadDir }}</span>
              </template>
              <template #label>
                下载位置
              </template>
            </Cell>
            <Cell>
              <template #title>
                {{ formatSize(info.totalSize - info.leftUntilDone) }}({{ calRatio(info.totalSize - info.leftUntilDone,
                info.totalSize)

                }}) / {{ formatSize(info.totalSize) }}
              </template>
              <template #label>
                已完成 / 总大小
              </template>
            </Cell>
            <Cell>
              <template #title>
                {{ info.status }} |
                <Icon name="arrow-down" />{{ formatSize(info.rateDownload) }}/s |
                <Icon name="arrow-up" />{{ formatSize(info.rateUpload) }}/s
              </template>
              <template #label>
                状态
              </template>
            </Cell>
          </template>
        </template>
      </CollapseItem>
    </Collapse>

    <div class="menu-btn">
      <Popover v-model:show="menuShow" :actions="menuActions" placement="left-end" @select="menuSelect">
        <template #reference>
          <Button round plain icon="bars" type="primary"></Button>
        </template>
      </Popover>
    </div>

    <ActionSheet v-model:show="pushShow" title="推送下载">
      <PushTorrent ref="pushTorrent" @close="() => { loadModel(); pushShow = false; }" />
    </ActionSheet>

    <ActionSheet v-model:show="linkShow" title="关联到下载器">
      <LinkClient ref="linkClient" @close="() => { loadModel(); linkShow = false; }" />
    </ActionSheet>

    <ActionSheet v-model:show="recognizeShow" title="识别">
      <Recognize :id="model.id" @close="() => { loadModel(); recognizeShow = false; }" />
    </ActionSheet>

    <!-- 季数选择器 -->
    <Popup v-model:show="seasonPicker" position="bottom">
      <Picker :columns="seasonOptions" @confirm="changeSeason" @cancel="seasonPicker = false" />
    </Popup>
  </div>
</template>
    
<script name="torrent-detail-mobile" setup>
import { Empty, Collapse, CollapseItem, Row, Col, Cell, ActionSheet, Button, Popover, Notify, Icon, Popup, Picker } from 'vant';
import PushTorrent from '@/mobile/Torrent/Push.vue'
import LinkClient from '@/mobile/Torrent/LinkClient.vue';
import Recognize from '@/mobile/Torrent/Recognize.vue';

import { reactive, ref, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import BaseApi from '@/api/api.js';
import TorrentApi from '@/api/TorrentApi';
import MediaApi from '@/api/MediaApi';
import CommonUtil from '@/utils/CommonUtil.js'

import store from '@/store'

const route = useRoute()

const module = 'torrent';

const modelId = route.query.id;

const activeNames = ref(['1', '2']);





const siteOptions = store.state.siteOptions;
const categoryOptions = store.state.categoryOptions;
const clientOptions = store.state.clientOptions;
const libraryOptions = store.state.libraryOptions;

const optionName = (id, options) => {
  return options.find(item => item.id === id)?.name
}

const model = ref({});
const info = ref({});

// common methods
const formatDate = (val) => {
  return CommonUtil.formatTimestamp(val)
};
const calRatio = (a, total) => {
  let temp = a / total * 100
  return temp.toFixed(2) + '%'
};
const formatSize = (val) => {
  return CommonUtil.formatSize(val)
}

const loadModel = () => {
  BaseApi.find(module, modelId).then(response => {
    if (response.data.code === 1) {
      if (response.data.data) {
        model.value = response.data.data

        if (model.value.status === 'linked') {
          loadInfoInClient();
        } else if (model.value.status === 'unlink') {
          menuActions[1].disabled = false
        }
      }

    } else {
      Notify({ type: 'danger', message: `数据加载失败：${response.data.message}` });
    }
  }).then(() => {
  })
};

const loadInfoInClient = () => {
  TorrentApi.infoInClient({ id: modelId }).then(response => {
    if (response.data.code === 1) {
      if (response.data.data)
        info.value = response.data.data
    } else {
      Notify({ type: 'danger', message: `数据加载失败：${response.data.message}` });
    }
  }).then(() => {
  })
};

const doActioning = ref(false);
const doAction = (action) => {
  if (!modelId && !action) return
  doActioning.value = true
  TorrentApi.doAction(modelId, action).then(response => {
    if (response.data.code === 1) {
      setTimeout(() => {
        loadInfoInClient();
        Notify({ type: 'success', message: '操作成功' });
        doActioning.value = false;
      }, 3000)
    } else {
      Notify({ type: 'danger', message: `操作失败：${response.data.message}` });
    }
  }).catch((error) => {
    doActioning.value = false
    Notify({ type: 'danger', message: `操作失败：${error.message}` });
  }).then(() => {
  })
};

//
const pushTorrent = ref(null);
const pushShow = ref(false);

const linkClient = ref(null);
const linkShow = ref(false);

const recognizeShow = ref(false);
const recognizeList = ref([]);

const menuShow = ref(false);
const menuActions = reactive([
  { text: '关联到下载器', disabled: false },
  { text: '推送下载', disabled: true },
  { text: '识别', disabled: false },
]);

model.value.status === 'linked'
const menuSelect = (action, index) => {
  // console.log(action);
  if (index === 0) {
    linkShow.value = true;
    nextTick(() => {
      linkClient.value.initModel({
        id: model.value.id,
        clientid: model.value.clientid,
        hashString: model.value.hashString,
      });
    })
  } else if (index === 1) {
    pushShow.value = true;
    nextTick(() => {
      pushTorrent.value.initModel({
        id: model.value.id,
        clientid: model.value.clientid,
      });
    })
  } else if (index === 2) {
    recognizeShow.value = true;
  }
};


// 季数选择器
const seasonPicker = ref(false)
const seasonOptions = ref([])
const showSeasonPicker = async () => {
  if (!seasonOptions.value.length) {
    const response = await MediaApi.getByTmdbid({ tmdbid: model.value.tmdbid, type: 'tv' })
    if (response.data.code === 1) {
      if (response.data.data && response.data.data.info) {
        const mediaInfo = JSON.parse(response.data.data.info)
        if (mediaInfo.seasons) {
          seasonOptions.value = mediaInfo.seasons.map(season => {
            return {
              text: `${season.season_number} - ${season.name}`,
              value: season.season_number,
            }
          })
        }
      }
    }
  }
  seasonPicker.value = true
}
const changeSeason = (val) => {
  BaseApi.update(module, { id: model.value.id, season: val.value }).then(response => {
    if (response.data.code === 1) {
      model.value.season = val.value
      Notify({ type: 'success', message: '操作成功' });
    } else {
      Notify({ type: 'danger', message: `操作失败：${response.data.message}` });
    }
  }).catch((error) => {
    Notify({ type: 'danger', message: `操作失败：${error.message}` });
  }).then(() => {
    seasonPicker.value = false
  })
}

// init
loadModel();

</script>
<style scoped>
.menu-btn {
  position: fixed;
  bottom: 20px;
  /* right: 20px; */
  width: 100%;
  text-align: right;
  padding-right: 20px;
}
</style>